package com.github.pig.goods.bussiness.product.controller;
import com.baomidou.mybatisplus.mapper.Condition;
import com.github.pig.common.util.ConvertMapUtil;
import com.github.pig.common.util.UserUtils;
import com.github.pig.goods.bussiness.product.entity.TAgent;
import com.github.pig.goods.bussiness.product.entity.TProduct;
import com.github.pig.goods.bussiness.product.service.ITAgentService;
import com.github.pig.goods.bussiness.product.service.ITProductService;
import com.github.pig.goods.common.util.CreateQRForProductAndSN;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;


import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.util.Query;
import com.github.pig.common.util.R;
import com.github.pig.common.web.BaseController;
import com.github.pig.goods.bussiness.product.service.ITAgentProductService;
import com.github.pig.goods.bussiness.product.entity.TAgentProduct;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;

import javax.servlet.http.HttpServletRequest;
import java.net.URL;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 代理商产品关联表 前端控制器
 * </p>
 *
 * @author Carlos123
 * @since 2018-08-27
 */
@Slf4j
@RestController
@RequestMapping("/tAgentProduct")
@Api(value = "TAgentProductController", description = "代理商产品关联表")
public class TAgentProductController extends BaseController{


    @Autowired
    private ITAgentProductService tAgentProductService;
    @Autowired
    private ITProductService tProductService;
    @Autowired
    private ITAgentService tAgentService;


/**
 * 通过ID查询
 *
 * @param id ID
 * @return TAgentProduct
 */
@GetMapping("/{id}")
@ApiOperation(value = "  按id查询", httpMethod = "GET", notes = "  按id查询")
@ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "long", paramType = "path")
public R<TAgentProduct> get(@PathVariable String id){
    return new R<>(tAgentProductService.selectById(id));
}


/**
* 分页查询信息
*
* @param params 分页对象
* @return 分页对象
*/
@RequestMapping("/page")
@ApiOperation(value = "分页查询 参数为TAgentProduct表中的属性",httpMethod = "GET", notes = "TAgentProduct列表方法")
@ApiImplicitParam(name = "查询参数", value = "TAgentProduct参数", required = true, dataType = "Map", paramType = "path")
public Page page(@RequestParam Map<String, Object> params){
    params = ConvertMapUtil.convertMapOfUnderLine(params);
    params.put(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
    return tAgentProductService.selectPage(new Query<>(params),new EntityWrapper<>());
}

/**
 * 添加
 * @param  tAgentProduct 实体
 * @return success/false
 */
@PostMapping("/add")
@ApiOperation(value = "新增实体 参数为TAgentProduct实体", notes = "TAgentProduct新增方法")
@ApiImplicitParam(name = "tAgentProduct", value = "TAgentProduct实体", required = true, dataType = "TAgentProduct", paramType = "path")
public R<Boolean> add( TAgentProduct tAgentProduct,HttpServletRequest request){
    if (tAgentProduct.getAgentId() != null&&tAgentProduct.getProductId()!=null){
        TProduct p = tProductService.getProductById(tAgentProduct.getProductId());
        TAgent a = tAgentService.selectById(tAgentProduct.getAgentId());
        log.info("代理商：{}",a);
        log.info("产品为：{}",p);
        if (p != null&& a!=null) {
            URL QRUrl = null;
            System.out.println("代理商编号"+a.getSn());
            try {
                QRUrl = CreateQRForProductAndSN.getQRCode(request,
                        p.getSameStyleNum()==null?"000000":p.getSameStyleNum(),
                        tAgentProduct.getProductId(),
                        a.getSn()==null?"0000":a.getSn());
            } catch (Exception e) {
                e.printStackTrace();
            }
            tAgentProduct.setQr(QRUrl.toString().substring(0,QRUrl.toString().indexOf("?")));
            tAgentProduct.setCreateTime(new Date());
            tAgentProduct.setDelFlag(0);
            tAgentProduct.setCreator(UserUtils.getUser());
            return new R<>(tAgentProductService.insert(tAgentProduct));
        }else {
            return new R<>(false,"无此产品或代理商");
        }

    }
            return new R<>(false,"参数错误");
}


    /**
     * 添加
     * @param  tAgentProductList 批量定价
     * @return success/false
     */
    @PostMapping("/addBatch")
    @ApiOperation(value = "产品关联代理商 TAgentProduct", notes = "产品关联代理商")
    public R<Boolean> add(@RequestBody List<TAgentProduct> tAgentProductList, HttpServletRequest request){
        tAgentProductList.forEach(o->{
            TProduct p = tProductService.getProductById(o.getProductId());
            TAgent a = tAgentService.selectById(o.getAgentId());

                    if (p != null&& a!=null) {
                        log.info("代理商：{}",a.getSn());
                        log.info("产品为：{}",p.getSameStyleNum());
                        URL QRUrl = null;
                        System.out.println("代理商编号" + a.getSn());
                        try {
                            QRUrl = CreateQRForProductAndSN.getQRCode(request,
                                    p.getSameStyleNum() == null ? "000000" : p.getSameStyleNum(),
                                    o.getProductId(),
                                    a.getSn() == null ? "0000" : a.getSn());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        o.setQr(QRUrl.toString().substring(0, QRUrl.toString().indexOf("?")));

                    }
            o.setId(p.getId());
            o.setCreateTime(new Date());
            o.setDelFlag(0);
            o.setCreator(UserUtils.getUser());
        });
        return new R<>(tAgentProductService.insertOrUpdateAllColumnBatch(tAgentProductList));
    }



/**
 * 条件删除 （取消关联）
 * @param  params
 * @return success/false
 */
@RequestMapping("/delete")
@ApiOperation(value = "取消关联",httpMethod = "GET", notes = "取消关联")
@ApiImplicitParam(name = "取消关联", value = "取消关联", required = true, dataType = "Map", paramType = "path")
public R<Boolean> deleteParam(@RequestParam Map<String, Object> params){
    return new R<>(tAgentProductService.deleteByMap(ConvertMapUtil.convertMapOfUnderLine(params)));
}



    /**
     * 条件删除 （取消关联）
     * @param
     * @return success/false
     */
    @PostMapping("/deleteBatch/{agentId}")
    @ApiOperation(value = "取消关联",httpMethod = "Post", notes = "取消关联")
    @ApiImplicitParam(name = "取消关联", value = "取消关联", required = true, dataType = "Map", paramType = "path")
    public R<List> deleteBatch(@PathVariable String agentId,@RequestBody List<String> idList){
        if (agentId == null&&idList.size()>-1) {
            return new R<>(null, "代理商或产品不可为空！！");
        }
        List<String> resultList = new LinkedList();
        for (int i =0 ;i<idList.size();i++){
            TAgentProduct tp = tAgentProductService.selectOne(Condition.create().eq("agent_id",agentId).eq("product_id",idList.get(i)));

            if (tp != null) {
                boolean tag = tAgentProductService.deleteById(tp);
                if (tag) {
                    resultList.add("【"+idList.get(i)+":取消关联成功】");
                }else {
                    resultList.add("【"+idList.get(i)+":取消关联失败】");
                }
            }else {
                    resultList.add("【"+idList.get(i)+":该代理商无代理该产品！】");
            }
        }
        return  new R<>(resultList);
    }



/**
 * 删除
 * @param id ID
 * @return success/false
 */
@DeleteMapping("/{id}")
@ApiOperation(value = "按id删除", notes = "TAgentProduct删除")
@ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "long", paramType = "path")
public R<Boolean> delete(@PathVariable String id){return new R<>(tAgentProductService.deleteById(id));}

/**
 * 编辑
 * @param  tAgentProduct 实体
 * @return success/false
 */
@PutMapping("/update")
@ApiOperation(value = "修改 参数为TAgentProduct实体", notes = "TAgentProduct修改")
@ApiImplicitParam(name = "tAgentProduct", value = "TAgentProduct实体", required = true, dataType = "TAgentProduct", paramType = "path")
public R<Boolean> edit(@RequestBody TAgentProduct tAgentProduct){
    return new R<>(tAgentProductService.updateById(tAgentProduct));
}


}
